{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Classifying Names with a Character-Level RNN\n",
    "\n",
    "\n",
    "Adapted from [pytorch tutorial](https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html)\n",
    "**Author**: `Sean Robertson <https://github.com/spro/practical-pytorch>`\n",
    "\n",
    "We will be building and training a basic character-level RNN to classify\n",
    "words. A character-level RNN reads words as a series of characters -\n",
    "outputting a prediction and \"hidden state\" at each step, feeding its\n",
    "previous hidden state into each next step. We take the final prediction\n",
    "to be the output, i.e. which class the word belongs to.\n",
    "\n",
    "Specifically, we'll train on a few thousand surnames from 18 languages\n",
    "of origin, and predict which language a name is from based on the\n",
    "spelling:\n",
    "\n",
    "\n",
    "**Recommended Reading:**\n",
    "\n",
    "To know more about RNNs and how they work:\n",
    "\n",
    "-  [The Unreasonable Effectiveness of Recurrent Neural\n",
    "   Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness) shows a bunch of real life examples\n",
    "-  [Understanding LSTM Networks](http://colah.github.io/posts/2015-08-Understanding-LSTMs) is about LSTMs specifically but also informative about RNNs in\n",
    "   general\n",
    "\n",
    "## Preparing the Data\n",
    "\n",
    "   Download the data from\n",
    "   [here](https://download.pytorch.org/tutorial/data.zip)\n",
    "   and extract it to the data directory.\n",
    "\n",
    "Included in the ``data/names`` directory are 18 text files named as\n",
    "\"[Language].txt\". Each file contains a bunch of names, one name per\n",
    "line, mostly romanized (but we still need to convert from Unicode to\n",
    "ASCII).\n",
    "\n",
    "We'll end up with a dictionary of lists of names per language,\n",
    "``{language: [names ...]}``. The generic variables \"category\" and \"line\"\n",
    "(for language and name in our case) are used for later extensibility.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import unicode_literals, print_function, division\n",
    "from io import open\n",
    "import glob\n",
    "import os\n",
    "\n",
    "#this line needs to be modified!\n",
    "all_files = '/home/lelarge/data/names/*.txt'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def findFiles(path): return glob.glob(path)\n",
    "\n",
    "\n",
    "\n",
    "print(findFiles(all_files))\n",
    "\n",
    "import unicodedata\n",
    "import string\n",
    "\n",
    "all_letters = string.ascii_letters + \" .,;'\"\n",
    "n_letters = len(all_letters)\n",
    "\n",
    "# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427\n",
    "def unicodeToAscii(s):\n",
    "    return ''.join(\n",
    "        c for c in unicodedata.normalize('NFD', s)\n",
    "        if unicodedata.category(c) != 'Mn'\n",
    "        and c in all_letters\n",
    "    )\n",
    "\n",
    "print(unicodeToAscii('Ślusàrski'))\n",
    "\n",
    "# Build the category_lines dictionary, a list of names per language\n",
    "category_lines = {}\n",
    "all_categories = []\n",
    "\n",
    "# Read a file and split into lines\n",
    "def readLines(filename):\n",
    "    lines = open(filename, encoding='utf-8').read().strip().split('\\n')\n",
    "    return [unicodeToAscii(line) for line in lines]\n",
    "\n",
    "for filename in findFiles(all_files):\n",
    "    category = os.path.splitext(os.path.basename(filename))[0]\n",
    "    all_categories.append(category)\n",
    "    lines = readLines(filename)\n",
    "    category_lines[category] = lines\n",
    "\n",
    "n_categories = len(all_categories)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have ``category_lines``, a dictionary mapping each category\n",
    "(language) to a list of lines (names). We also kept track of\n",
    "``all_categories`` (just a list of languages) and ``n_categories`` for\n",
    "later reference.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(category_lines['Italian'][:5])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Turning Names into Tensors\n",
    "--------------------------\n",
    "\n",
    "Now that we have all the names organized, we need to turn them into\n",
    "Tensors to make any use of them.\n",
    "\n",
    "To represent a single letter, we use a \"one-hot vector\" of size\n",
    "``<1 x n_letters>``. A one-hot vector is filled with 0s except for a 1\n",
    "at index of the current letter, e.g. ``\"b\" = <0 1 0 0 0 ...>``.\n",
    "\n",
    "To make a word we join a bunch of those into a 2D matrix\n",
    "``<line_length x 1 x n_letters>``.\n",
    "\n",
    "That extra 1 dimension is because PyTorch assumes everything is in\n",
    "batches - we're just using a batch size of 1 here.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "# Find letter index from all_letters, e.g. \"a\" = 0\n",
    "def letterToIndex(letter):\n",
    "    return all_letters.find(letter)\n",
    "\n",
    "# Just for demonstration, turn a letter into a <1 x n_letters> Tensor\n",
    "def letterToTensor(letter):\n",
    "    tensor = torch.zeros(1, n_letters)\n",
    "    tensor[0][letterToIndex(letter)] = 1\n",
    "    return tensor\n",
    "\n",
    "# Turn a line into a <line_length x 1 x n_letters>,\n",
    "# or an array of one-hot letter vectors\n",
    "def lineToTensor(line):\n",
    "    tensor = torch.zeros(len(line), 1, n_letters)\n",
    "    for li, letter in enumerate(line):\n",
    "        tensor[li][0][letterToIndex(letter)] = 1\n",
    "    return tensor\n",
    "\n",
    "print(letterToTensor('J'))\n",
    "\n",
    "print(lineToTensor('Jones').size())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Creating the Network\n",
    "====================\n",
    "\n",
    "Before autograd, creating a recurrent neural network in Torch involved\n",
    "cloning the parameters of a layer over several timesteps. The layers\n",
    "held hidden state and gradients which are now entirely handled by the\n",
    "graph itself. This means you can implement a RNN in a very \"pure\" way,\n",
    "as regular feed-forward layers.\n",
    "\n",
    "This RNN module (mostly copied from `the PyTorch for Torch users tutorial <http://pytorch.org/tutorials/beginner/former_torchies/nn_tutorial.html#example-2-recurrent-net>`__)\n",
    "is just 2 linear layers which operate on an input and hidden state, with\n",
    "a LogSoftmax layer after the output.\n",
    "\n",
    "<img src=Z2xbySO.png>\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "class RNN(nn.Module):\n",
    "    def __init__(self, input_size, hidden_size, output_size):\n",
    "        super(RNN, self).__init__()\n",
    "\n",
    "        self.hidden_size = hidden_size\n",
    "\n",
    "        self.i2h = nn.Linear(input_size + hidden_size, hidden_size)\n",
    "        self.i2o = nn.Linear(input_size + hidden_size, output_size)\n",
    "        self.softmax = nn.LogSoftmax(dim=1)\n",
    "\n",
    "    def forward(self, input, hidden):\n",
    "        combined = torch.cat((input, hidden), 1)\n",
    "        hidden = self.i2h(combined)\n",
    "        output = self.i2o(combined)\n",
    "        output = self.softmax(output)\n",
    "        return output, hidden\n",
    "\n",
    "    def initHidden(self):\n",
    "        return torch.zeros(1, self.hidden_size)\n",
    "\n",
    "n_hidden = 128\n",
    "rnn = RNN(n_letters, n_hidden, n_categories)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To run a step of this network we need to pass an input (in our case, the\n",
    "Tensor for the current letter) and a previous hidden state (which we\n",
    "initialize as zeros at first). We'll get back the output (probability of\n",
    "each language) and a next hidden state (which we keep for the next\n",
    "step).\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "input = letterToTensor('A')\n",
    "hidden = torch.zeros(1, n_hidden)\n",
    "\n",
    "output, next_hidden = rnn(input, hidden)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(next_hidden)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the sake of efficiency we don't want to be creating a new Tensor for\n",
    "every step, so we will use ``lineToTensor`` instead of\n",
    "``letterToTensor`` and use slices. This could be further optimized by\n",
    "pre-computing batches of Tensors.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input = lineToTensor('Albert')\n",
    "hidden = torch.zeros(1, n_hidden)\n",
    "\n",
    "output, next_hidden = rnn(input[0], hidden)\n",
    "print(output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see the output is a ``<1 x n_categories>`` Tensor, where\n",
    "every item is the likelihood of that category (higher is more likely).\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Training\n",
    "========\n",
    "Preparing for Training\n",
    "----------------------\n",
    "\n",
    "Before going into training we should make a few helper functions. The\n",
    "first is to interpret the output of the network, which we know to be a\n",
    "likelihood of each category. We can use ``Tensor.topk`` to get the index\n",
    "of the greatest value:\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def categoryFromOutput(output):\n",
    "    top_n, top_i = output.topk(1)\n",
    "    category_i = top_i[0].item()\n",
    "    return all_categories[category_i], category_i\n",
    "\n",
    "print(categoryFromOutput(output))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will also want a quick way to get a training example (a name and its\n",
    "language):\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "\n",
    "def randomChoice(l):\n",
    "    return l[random.randint(0, len(l) - 1)]\n",
    "\n",
    "def randomTrainingExample():\n",
    "    category = randomChoice(all_categories)\n",
    "    line = randomChoice(category_lines[category])\n",
    "    category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long)\n",
    "    line_tensor = lineToTensor(line)\n",
    "    return category, line, category_tensor, line_tensor\n",
    "\n",
    "for i in range(10):\n",
    "    category, line, category_tensor, line_tensor = randomTrainingExample()\n",
    "    print('category =', category, '/ line =', line)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Training the Network\n",
    "--------------------\n",
    "\n",
    "Now all it takes to train this network is show it a bunch of examples,\n",
    "have it make guesses, and tell it if it's wrong.\n",
    "\n",
    "For the loss function ``nn.NLLLoss`` is appropriate, since the last\n",
    "layer of the RNN is ``nn.LogSoftmax``.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "criterion = nn.NLLLoss()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each loop of training will:\n",
    "\n",
    "-  Create input and target tensors\n",
    "-  Create a zeroed initial hidden state\n",
    "-  Read each letter in and\n",
    "\n",
    "   -  Keep hidden state for next letter\n",
    "\n",
    "-  Compare final output to target\n",
    "-  Back-propagate\n",
    "-  Return the output and loss\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "learning_rate = 0.005 # If you set this too high, it might explode. If too low, it might not learn\n",
    "\n",
    "def train(category_tensor, line_tensor):\n",
    "    hidden = rnn.initHidden()\n",
    "\n",
    "    rnn.zero_grad()\n",
    "\n",
    "    for i in range(line_tensor.size()[0]):\n",
    "        output, hidden = rnn(line_tensor[i], hidden)\n",
    "\n",
    "    loss = criterion(output, category_tensor)\n",
    "    loss.backward()\n",
    "\n",
    "    # Add parameters' gradients to their values, multiplied by learning rate\n",
    "    for p in rnn.parameters():\n",
    "        p.data.add_(-learning_rate, p.grad.data)\n",
    "\n",
    "    return output, loss.item()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we just have to run that with a bunch of examples. Since the\n",
    "``train`` function returns both the output and loss we can print its\n",
    "guesses and also keep track of loss for plotting. Since there are 1000s\n",
    "of examples we print only every ``print_every`` examples, and take an\n",
    "average of the loss.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import math\n",
    "\n",
    "n_iters = 100000\n",
    "print_every = 5000\n",
    "plot_every = 1000\n",
    "\n",
    "\n",
    "\n",
    "# Keep track of losses for plotting\n",
    "current_loss = 0\n",
    "all_losses = []\n",
    "\n",
    "def timeSince(since):\n",
    "    now = time.time()\n",
    "    s = now - since\n",
    "    m = math.floor(s / 60)\n",
    "    s -= m * 60\n",
    "    return '%dm %ds' % (m, s)\n",
    "\n",
    "start = time.time()\n",
    "\n",
    "for iter in range(1, n_iters + 1):\n",
    "    category, line, category_tensor, line_tensor = randomTrainingExample()\n",
    "    output, loss = train(category_tensor, line_tensor)\n",
    "    current_loss += loss\n",
    "\n",
    "    # Print iter number, loss, name and guess\n",
    "    if iter % print_every == 0:\n",
    "        guess, guess_i = categoryFromOutput(output)\n",
    "        correct = '✓' if guess == category else '✗ (%s)' % category\n",
    "        print('%d %d%% (%s) %.4f %s / %s %s' % (iter, iter / n_iters * 100, timeSince(start), loss, line, guess, correct))\n",
    "\n",
    "    # Add current loss avg to list of losses\n",
    "    if iter % plot_every == 0:\n",
    "        all_losses.append(current_loss / plot_every)\n",
    "        current_loss = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plotting the Results\n",
    "--------------------\n",
    "\n",
    "Plotting the historical loss from ``all_losses`` shows the network\n",
    "learning:\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.ticker as ticker\n",
    "\n",
    "plt.figure()\n",
    "plt.plot(all_losses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Evaluating the Results\n",
    "======================\n",
    "\n",
    "To see how well the network performs on different categories, we will\n",
    "create a confusion matrix, indicating for every actual language (rows)\n",
    "which language the network guesses (columns). To calculate the confusion\n",
    "matrix a bunch of samples are run through the network with\n",
    "``evaluate()``, which is the same as ``train()`` minus the backprop.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Keep track of correct guesses in a confusion matrix\n",
    "confusion = torch.zeros(n_categories, n_categories)\n",
    "n_confusion = 10000\n",
    "\n",
    "# Just return an output given a line\n",
    "def evaluate(line_tensor):\n",
    "    hidden = rnn.initHidden()\n",
    "\n",
    "    for i in range(line_tensor.size()[0]):\n",
    "        output, hidden = rnn(line_tensor[i], hidden)\n",
    "\n",
    "    return output\n",
    "\n",
    "# Go through a bunch of examples and record which are correctly guessed\n",
    "for i in range(n_confusion):\n",
    "    category, line, category_tensor, line_tensor = randomTrainingExample()\n",
    "    output = evaluate(line_tensor)\n",
    "    guess, guess_i = categoryFromOutput(output)\n",
    "    category_i = all_categories.index(category)\n",
    "    confusion[category_i][guess_i] += 1\n",
    "\n",
    "# Normalize by dividing every row by its sum\n",
    "for i in range(n_categories):\n",
    "    confusion[i] = confusion[i] / confusion[i].sum()\n",
    "\n",
    "# Set up plot\n",
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(111)\n",
    "cax = ax.matshow(confusion.numpy())\n",
    "fig.colorbar(cax)\n",
    "\n",
    "# Set up axes\n",
    "ax.set_xticklabels([''] + all_categories, rotation=90)\n",
    "ax.set_yticklabels([''] + all_categories)\n",
    "\n",
    "# Force label at every tick\n",
    "ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n",
    "ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n",
    "\n",
    "# sphinx_gallery_thumbnail_number = 2\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can pick out bright spots off the main axis that show which\n",
    "languages it guesses incorrectly, e.g. Chinese for Korean, and Spanish\n",
    "for Italian. It seems to do very well with Greek, and very poorly with\n",
    "English (perhaps because of overlap with other languages).\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running on User Input\n",
    "---------------------\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(input_line, n_predictions=3):\n",
    "    print('\\n> %s' % input_line)\n",
    "    with torch.no_grad():\n",
    "        output = evaluate(lineToTensor(input_line))\n",
    "\n",
    "        # Get top N categories\n",
    "        topv, topi = output.topk(n_predictions, 1, True)\n",
    "        predictions = []\n",
    "\n",
    "        for i in range(n_predictions):\n",
    "            value = topv[0][i].item()\n",
    "            category_index = topi[0][i].item()\n",
    "            print('(%.2f) %s' % (value, all_categories[category_index]))\n",
    "            predictions.append([value, all_categories[category_index]])\n",
    "\n",
    "predict('Dovesky')\n",
    "predict('Jackson')\n",
    "predict('Satoshi')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Exercises\n",
    "=========\n",
    "\n",
    "-  Try with a different dataset of line -> category, for example:\n",
    "\n",
    "   -  Any word -> language\n",
    "   -  First name -> gender\n",
    "   -  Character name -> writer\n",
    "   -  Page title -> blog or subreddit\n",
    "\n",
    "-  Get better results with a bigger and/or better shaped network\n",
    "\n",
    "   -  Add more linear layers\n",
    "   -  Try the ``nn.LSTM`` and ``nn.GRU`` layers\n",
    "   -  Combine multiple of these RNNs as a higher level network\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:pytorch]",
   "language": "python",
   "name": "conda-env-pytorch-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
